from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Q
from rest_framework.authtoken.models import Token
from users.models import User
from weiwenhai_Oj.exceptions.data_exception import NotFoundException, ValidationException
from weiwenhai_Oj.exceptions.operation_exception import OperationFailedException
from django.contrib.auth.hashers import check_password, make_password
import jwt
from datetime import datetime, timedelta


class AuthService:
    """
    用户服务
    """

    def register(self, user_data):
        """
        用户注册服务
        """
        user = User.objects.create(**user_data)
        return self._generate_token(user)

    def login_in(self, username, password):
        """
        用户登录服务
        """
        try:
            user = User.objects.get(username=username)
            if user.check_password(password):
                return self._generate_token(user)
            raise ValueError("密码错误")
        except User.DoesNotExist:
            raise ValueError("用户不存在")

    def logout(self, token):
        """
        用户注销服务
        """
        try:
            token = Token.objects.get(key=token)
            token.delete()
            return True
        except Token.DoesNotExist:
            return False

    def update_profile(self, user, profile_data):
        """
        更新用户信息服务
        """
        for key, value in profile_data.items():
            if hasattr(user, key) and value is not None:
                setattr(user, key, value)
        user.save()
        return user

    def change_password(self, user, old_password, new_password):
        """
        修改密码服务
        """
        if not user.check_password(old_password):
            raise ValidationException("旧密码不正确")
        
        user.password = make_password(new_password)
        user.save()
        return True

    def get_user_statistics(self, user):
        """
        获取用户统计信息
        """
        from submission.models.submission_model import SubmissionModel
        
        total_submissions = SubmissionModel.objects.filter(user=user).count()
        accepted_submissions = SubmissionModel.objects.filter(
            user=user,
            status='AC'
        ).count()
        solved_problems = SubmissionModel.objects.filter(
            user=user,
            status='AC'
        ).values('problem').distinct().count()

        return {
            'total_submissions': total_submissions,
            'accepted_submissions': accepted_submissions,
            'solved_problems': solved_problems
        }

    def _generate_token(self, user):
        """
        生成用户认证token
        """
        token, _ = Token.objects.get_or_create(user=user)
        return token.key
